import { Button, Form, Input, Modal, Select, Table } from 'antd';
import axios from 'axios';
import React, { useEffect, useState } from 'react';
import config from '../config';

const DeviceInfo = () => {
  const [devices, setDevices] = useState([]);
  const [selectedFunction, setSelectedFunction] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();

  const functionsMapping = {
    'reservoir_temperature': '环境温度',
    'water_as': '砷含量',
    'water_bod5': '五日生化需氧量',
    'water_c2n2': '氰化物含量',
    'water_c6h5oh': '挥发酚含量',
    'water_cd': '镉含量',
    'water_cod': '化学需氧量',
    'water_coli_group': '粪大肠杆菌群',
    'water_conductivity': '电导率',
    'water_cr': '铬含量',
    'water_cu': '铜含量',
    'water_dissolved_oxygen': '氧溶解量',
    'water_entire_n': '总氨量',
    'water_entire_p': '总磷量',
    'water_f': '氟化物含量',
    'water_hg': '汞含量',
    'water_las': '阴离子表面活性剂含量',
    'water_mno4': '高锰酸盐含量指数',
    'water_nh3n': '氨氨量',
    'water_pb': '铅含量',
    'water_petroleum': '石油类含量',
    'water_ph': 'pH值',
    'water_s': '硫化物含量',
    'water_se': '硒含量',
    'water_temperature': '水温',
    'water_zn': '锌含量'
  };

  const functionsList = Object.keys(functionsMapping);

  useEffect(() => {
    const token = localStorage.getItem('token');
    axios.get(`${config.apiUrl}/deviceInfo/showAll`, {
      headers: {
        'token': token
      }
    })
    .then(response => {
      const tableData = response.data.data.map(item => ({
        key: item.id,
        stcd: item.stcd,
        functions: item.functions,
        position: item.position,
        status: item.status
      }));
      setDevices(tableData);
    })
    .catch(error => {
      console.error('Error fetching devices:', error);
    });
  }, []);

  const handleFunctionChange = (event) => {
    const functionValue = event.target.value;
    setSelectedFunction(functionValue);

    const token = localStorage.getItem('token');
    if (functionValue) {
      axios.get(`${config.apiUrl}/deviceInfo/selectByFunctions?functions=${functionValue}`, {
        headers: {
          'token': token
        }
      })
      .then(response => {
        const tableData = response.data.data.map(item => ({
          key: item.id,
          stcd: item.stcd,
          functions: item.functions,
          position: item.position,
          status: item.status
        }));
        setDevices(tableData);
      })
      .catch(error => {
        console.error('Error fetching devices:', error);
      });
    } else {
      axios.get(`${config.apiUrl}/deviceInfo/showAll`, {
        headers: {
          'token': token
        }
      })
      .then(response => {
        const tableData = response.data.data.map(item => ({
          key: item.id,
          stcd: item.stcd,
          functions: item.functions,
          position: item.position,
          status: item.status
        }));
        setDevices(tableData);
      })
      .catch(error => {
        console.error('Error fetching devices:', error);
      });
    }
  };

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleOk = () => {
    form.validateFields().then(values => {
      const token = localStorage.getItem('token');
      axios.post(`${config.apiUrl}/deviceInfo/saveOrUpdateDeviceInfo`, values, {
        headers: {
          'token': token
        }
      })
      .then(response => {
        if (response.data.code === 200) {
          // 重新加载设备数据
          handleFunctionChange({ target: { value: selectedFunction } });
          form.resetFields(); // 重置表单
          setIsModalVisible(false); // 关闭模态框
        }
      })
      .catch(error => {
        console.error('Error saving or updating device info:', error);
      });
    });
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const columns = [
    { title: 'ID', dataIndex: 'key', key: 'key' },
    { title: 'STCD', dataIndex: 'stcd', key: 'stcd' },
    { title: '功能', dataIndex: 'functions', key: 'functions' },
    { title: '位置', dataIndex: 'position', key: 'position' },
    { title: '状态', dataIndex: 'status', key: 'status' },
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Button type="primary" size="small" onClick={showModal} style={{ width: '40px', height: '40px', padding: 0 }}>+</Button>
          <span style={{ marginLeft: '8px' }}>添加设备</span>
        </div>
        <select value={selectedFunction} onChange={handleFunctionChange} style={{ marginLeft: '8px' }}>
          <option value="">功能筛选</option>
          {functionsList.map(func => (
            <option key={func} value={func}>{functionsMapping[func]}</option>
          ))}
        </select>
      </div>
      <Table 
        dataSource={devices} 
        columns={columns} 
        pagination={{ pageSize: 10 }}
      />
      <Modal title="添加设备" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <Form form={form} layout="vertical">
          <Form.Item name="stcd" label="STCD" rules={[{ required: true, message: '请输入STCD' }]}>
            <Input placeholder="输入STCD" />
          </Form.Item>
          <Form.Item name="functions" label="Functions" rules={[{ required: true, message: '请输入Functions' }]}>
            <Select>
              {functionsList.map(func => (
                <Select.Option key={func} value={func}>{functionsMapping[func]}</Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="position" label="Position" rules={[{ required: true, message: '请输入Position' }]}>
            <Input placeholder="输入Position" />
          </Form.Item>
          <Form.Item name="status" label="Status" rules={[{ required: true, message: '请输入Status' }]}>
            <Input placeholder="输入Status" type="number" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default DeviceInfo;
